package cn.hxzy.zyicon.service.impl;

import cn.hxzy.zyicon.entity.Resource;
import cn.hxzy.zyicon.entity.Role;
import cn.hxzy.zyicon.repository.ResourceRepository;
import cn.hxzy.zyicon.repository.RoleRepository;
import cn.hxzy.zyicon.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;


/**
 * (Role)表服务实现类
 *
 * @author makejava
 * @since 2020-08-15 10:25:33
 */
@Service("roleService")
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private ResourceRepository resourceRepository;

    @Override
    public void delete(Integer id) {
        roleRepository.deleteById(id);
    }

    @Override
    public void save(Role role) {
        roleRepository.save(role);
    }

    @Override
    public List<Role> findAll() {
        return roleRepository.findAll();
    }

    @Override
    public Role findById(Integer id) {
        Optional<Role> byId = roleRepository.findById(id);
        if (byId.isPresent()) {
            return byId.get();
        }
        return null;
    }

    @Override
    public void update(Role role) {
        Optional<Role> byId = roleRepository.findById(role.getId());
        if (byId.isPresent()) {
        role.setResourceList(byId.get().getResourceList());
        }
        roleRepository.save(role);
    }

    @Override
    public List<Resource> findNotHave(Integer id) {
        Optional<Role> byId = roleRepository.findById(id);
        if (byId.isPresent()) {
            Role role=byId.get();
            List<Resource> resourceList = role.getResourceList();
            List<Integer> collect = resourceList.stream().map(Resource::getId).collect(Collectors.toList());
            if (collect.isEmpty()) {
             return resourceRepository.findAll();
            }
            return resourceRepository.findByIdNotIn(collect);
        }
        return null;
    }

    @Override
    public void authorize(Integer resourceId, Integer roleId) {
        Optional<Role> byId = roleRepository.findById(roleId);
        if (byId.isPresent()) {
            Role role=byId.get();
            List<Resource> resourceList = role.getResourceList();
            boolean flag = false;
            for (int i = 0; i < resourceList.size(); i++) {
                if (resourceList.get(i).getId().equals(resourceId)) {
                    flag=true;
                    resourceList.remove(i);
                }
            }
            if (!flag) {
                Resource resource=new Resource();
                resource.setId(resourceId);
                resourceList.add(resource);
            }
            roleRepository.save(role);
        }
    }


}